Slicing in Python

Python allows slicing a collection into a smaller subset

Let's first create a list


In [6]:
l = [1, 2, 3, 4, 5, 6, 7, 8 ,9 ,10]

Let's say I wanted to get only the first four elements of the list. How do we do that?

You can slice a list by specifying the starting index and ending index in the square brackets, separated by a :


In [7]:
first_four = l[0: 4]
print first_four


[1, 2, 3, 4]

What if we wanted to get all the elements except the first one?

If you don't specify anything after the :, python will get everything till the end of the list


In [8]:
second_to_last = l[1:]
print second_to_last


[2, 3, 4, 5, 6, 7, 8, 9, 10]

What if you wanted only the last two elements?

Hint: Use the -ve indices :)


In [10]:
print l[-2:]


[9, 10]

Exercise

  • How will you get values from 2nd position till the second last potion in the list?
  • How will you get the seonc last and thir last values?

Slicing Tuples

Slicing tuples is exactly similar to lists and left as an exercise for you to try out

Slicing Strings

Strings are very similar to lists, they are an ordered sequence of characters and thus they can also be sliced and diced


In [12]:
name = 'Bob The Builder'
print name


Bob The Builder

Indexing in strings is same as lists or tuples


In [13]:
print name[0]
print name[-1]
print name[2]


B
r
b

Slicing strings is the way to do substring operations in python


In [15]:
print name[0:3]


Bob

In [17]:
print name[4:7]


The

In [18]:
print name [-7: ]


Builder

In [ ]: